<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2006/12/22 10:13:57 $)
// $RCSfile: admin_customfields.php,v $ : $Revision: 1.11 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

if (!$staffauth->isAdmin()) {
	trigger_error("You do not have permission to access $PHP_SELF", E_USER_ERROR);
}

require_once ("./includes/functions_html.php");
require_once ("./includes/functions_customfields.php");
require_once ("./includes/functions_users.php");

$template->loadLanguageSection("customfields");

/**
* ###############################################
* FUNCTION DECLARATIONS
* ###############################################
*/
/**
* Callback for parsing custom field group data
*/
function _customFieldGroupFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	if ($record["grouptype"] == CUSTOMFIELD_USER)
	{
		$record["grouptype"] = $_SWIFT["language"]["grouptypeuser"];
	} else if ($record["grouptype"] == CUSTOMFIELD_USERGROUP) {
		$record["grouptype"] = $_SWIFT["language"]["grouptypeusergroup"];
	} else if ($record["grouptype"] == CUSTOMFIELD_STAFFTICKET) {
		$record["grouptype"] = $_SWIFT["language"]["grouptypestaffticket"];
	} else if ($record["grouptype"] == CUSTOMFIELD_USERTICKET) {
		$record["grouptype"] = $_SWIFT["language"]["grouptypeuserticket"];
	} else if ($record["grouptype"] == CUSTOMFIELD_STAFFUSERTICKET) { //Mahesh Slaria: Staff & user ticket creation
		$record["grouptype"] = $_SWIFT["language"]["grouptypestaffuserticket"];
	} else if ($record["grouptype"] == CUSTOMFIELD_TIMETRACK) {
		$record["grouptype"] = $_SWIFT["language"]["grouptypetimetrack"];
	} else if ($record["grouptype"] == CUSTOMFIELD_CONTACT) {
		$record["grouptype"] = $_SWIFT["language"]["grouptypecontact"];
	} else if ($record["grouptype"] == CUSTOMFIELD_EVENT) {
		$record["grouptype"] = $_SWIFT["language"]["grouptypeevent"];
	} else if ($record["grouptype"] == CUSTOMFIELD_TASK) {
		$record["grouptype"] = $_SWIFT["language"]["grouptypetask"];
	}

	$record["title"] = '<a href="index.php?_m=core&_a=editcfgroup&customfieldgroupid='. $record["customfieldgroupid"] .'" title="'. $_SWIFT["language"]["edit"] .'">'.$record["title"].'</a>';

	$record["options"] = '<a href="index.php?_m=core&_a=insertcfield&customfieldgroupid='. $record["customfieldgroupid"] .'" title="'. $_SWIFT["language"]["addfield"] .'"><img src="'. $_SWIFT["themepath"] .'icon_customfields.gif" border="0">&nbsp;'. $_SWIFT["language"]["addfield"] .'</a>&nbsp;&nbsp;&nbsp;<a href="index.php?_m=core&_a=editcfgroup&customfieldgroupid='. $record["customfieldgroupid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>'. iif($record["ismaster"]==1, '&nbsp;&nbsp;&nbsp;&nbsp;<img src="'. $_SWIFT["themepath"] .'icon_deletedisabled.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["cfgroupactconfirm"] .'\', \'index.php?_m=core&_a=managecfgroups&do=delete&customfieldgroupid='. $record["customfieldgroupid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;');
	return $record;
}

/**
* Mass Action: Delete Custom Field Groups
*/
function _maDeleteCustomFieldGroups()
{
	global $_SWIFT;

	if (!is_array($_POST["itemid"]))
	{
		return false;
	}

	deleteCustomFieldGroups($_POST["itemid"]);
}

/**
* Callback for parsing custom field data
*/
function _customFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["customfields.title"] = '<a href="index.php?_m=core&_a=editcfield&customfieldid='. $record["customfieldid"] .'" title="'. $_SWIFT["language"]["edit"] .'">'.$record["fieldtitle"].'</a>';
	$record["customfieldgroups.title"] = $record["grouptitle"];
	$record["customfields.displayorder"] = $record["fielddisplayorder"];

		$fields[] = array(FIELD_TEXT, $_SWIFT["language"]["field_text"], $_SWIFT["language"]["desc_field_text"], "icon_cfeditbox.gif");
		$fields[] = array(FIELD_TEXTAREA, $_SWIFT["language"]["field_textarea"], $_SWIFT["language"]["desc_field_textarea"], "icon_cfeditbox.gif");
		$fields[] = array(FIELD_PASSWORD, $_SWIFT["language"]["field_password"], $_SWIFT["language"]["desc_field_password"], "icon_cfpassword.gif");
		$fields[] = array(FIELD_CHECKBOX, $_SWIFT["language"]["field_checkbox"], $_SWIFT["language"]["desc_field_checkbox"], "icon_cfcheckbox.gif");
		$fields[] = array(FIELD_RADIO, $_SWIFT["language"]["field_radio"], $_SWIFT["language"]["desc_field_radio"], "icon_cfradio.gif");
		$fields[] = array(FIELD_SELECT, $_SWIFT["language"]["field_select"], $_SWIFT["language"]["desc_field_select"], "icon_cfselect.gif");
		$fields[] = array(FIELD_SELECTMULTIPLE, $_SWIFT["language"]["field_selectmultiple"], $_SWIFT["language"]["desc_field_selectmultiple"], "icon_cfselectmultiple.gif");
		$fields[] = array(FIELD_CUSTOM, $_SWIFT["language"]["field_custom"], $_SWIFT["language"]["desc_field_custom"], "icon_cfcustom.gif");

	$fieldtype = $record["fieldtype"];
	if ($fieldtype == FIELD_TEXT)
	{
		$typetitle = $_SWIFT["language"]["field_text"];
		$typeicon = "icon_cfeditbox.gif";
	} else if ($fieldtype == FIELD_TEXTAREA) {
		$typetitle = $_SWIFT["language"]["field_textarea"];
		$typeicon = "icon_cfeditbox.gif";
	} else if ($fieldtype == FIELD_PASSWORD) {
		$typetitle = $_SWIFT["language"]["field_password"];
		$typeicon = "icon_cfpassword.gif";
	} else if ($fieldtype == FIELD_CHECKBOX) {
		$typetitle = $_SWIFT["language"]["field_checkbox"];
		$typeicon = "icon_cfcheckbox.gif";
	} else if ($fieldtype == FIELD_RADIO) {
		$typetitle = $_SWIFT["language"]["field_radio"];
		$typeicon = "icon_cfradio.gif";
	} else if ($fieldtype == FIELD_SELECT) {
		$typetitle = $_SWIFT["language"]["field_select"];
		$typeicon = "icon_cfselect.gif";
	} else if ($fieldtype == FIELD_SELECTMULTIPLE) {
		$typetitle = $_SWIFT["language"]["field_selectmultiple"];
		$typeicon = "icon_cfselectmultiple.gif";
	} else if ($fieldtype == FIELD_CUSTOM) {
		$typetitle = $_SWIFT["language"]["field_custom"];
		$typeicon = "icon_cfcustom.gif";
	}

	$record["customfields.fieldtype"] = '<table width="150"  border="0" cellspacing="0" cellpadding="1" align="center"><tr><td width="1"><img src="'. $_SWIFT["themepath"].$typeicon .'" border="0" /></td><td><span class="smalltext">&nbsp;'. htmlspecialchars($typetitle) .'</span></td></tr></table>';

	$record["options"] = '<a href="index.php?_m=core&_a=editcfield&customfieldid='. $record["customfieldid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>'. iif($record["ismaster"]==1, '&nbsp;&nbsp;&nbsp;&nbsp;<img src="'. $_SWIFT["themepath"] .'icon_deletedisabled.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["cfdelconfirmmsg"] .'\', \'index.php?_m=core&_a=managecfields&do=delete&customfieldid='. $record["customfieldid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;');
	return $record;
}

/**
* Mass Action: Delete Custom Fields
*/
function _maDeleteCustomFields()
{
	global $_SWIFT;

	if (!is_array($_POST["itemid"]))
	{
		return false;
	}

	deleteCustomFields($_POST["itemid"]);
}


/**
* ###############################################
* MANAGE CUSTOM FIELD GROUPS
* ###############################################
*/
if ($eventaction == "managecfgroups")
{
	if ($_GET["do"] == "delete" && $_GET["customfieldgroupid"] != "")
	{
		$infomessage = $_SWIFT["language"]["cfgroupdelconfirm"];
		deleteCustomFieldGroups(array($_GET["customfieldgroupid"]));
	}

	if (trim($_REQUEST["insertcfgroup"]) != "")
	{
		$infomessage = sprintf($_SWIFT["language"]["cfgroupinsertconfirm"], htmlspecialchars($_GET["insertcfgroup"]));
	} else if (trim($_REQUEST["updatecfgroup"]) != "") {
		$infomessage = sprintf($_SWIFT["language"]["cfgroupupdateconfirm"], htmlspecialchars($_GET["updatecfgroup"]));
	}	

	$options["recordsperpage"] = "8";
	$options["sortby"] = "displayorder";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteCustomFieldGroups";

	$options["idname"] = "customfieldgroupid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["grouptitle"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'customfieldgroups` WHERE `title` LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_customFieldGroupFields";

	$fields[0]["name"] = "title";
	$fields[0]["title"] = $_SWIFT["language"]["grouptitle"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "grouptype";
	$fields[1]["title"] = $_SWIFT["language"]["grouptype"];
	$fields[1]["width"] = "230";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "displayorder";
	$fields[2]["title"] = $_SWIFT["language"]["displayorder"];
	$fields[2]["width"] = "120";
	$fields[2]["align"] = "center";

	$fields[3]["type"] = "custom";
	$fields[3]["name"] = "options";
	$fields[3]["title"] = $_SWIFT["language"]["options"];
	$fields[3]["width"] = "240";
	$fields[3]["align"] = "center";

	$grid = new Grid();

	$interface->adminHeader($_SWIFT["language"]["customfields"]." > ".$_SWIFT["language"]["managegroups"], 1);

	$interface->adminNavBar($_SWIFT["language"]["managegroups"], $_SWIFT["language"]["desc_customfieldgroups"] , 2);
	printInfoBox($infomessage);

	$grid->start("customfieldgroups", $_SWIFT["language"]["grouplist"], 'SELECT * FROM `'. TABLE_PREFIX .'customfieldgroups` $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'customfieldgroups`;', 'SELECT * FROM `'. TABLE_PREFIX .'customfieldgroups` WHERE `title` LIKE \'%$_searchstr%\' $_sortjoin;', $fields, $options);
	
	$grid->display("customfieldgroups");
	$interface->adminFooter();




/**
* ###############################################
* INSERT CUSTOM FIELD GROUP
* ###############################################
*/
} else if ($eventaction == "insertcfgroup") {
	if ($_POST["step"] == "1")
	{
		if (trim($_POST["title"]) == "" || trim($_POST["displayorder"]) == "" || trim($_POST["grouptype"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);	

			$customfieldgroupid = insertCustomFieldGroup($_POST["title"], $_POST["grouptype"], $_POST["displayorder"], $_POST["departmentid"]);

			printRedirect(sprintf($_SWIFT["language"]["cfgroupinsertconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=core&_a=managecfgroups&insertcfgroup=".urlencode($_POST["title"]));
			exit;
		}
	}

	$interface->adminHeader($_SWIFT["language"]["customfields"]." > ".$_SWIFT["language"]["insertgroup"], 1);

	$interface->adminNavBar($_SWIFT["language"]["insertgroup"], $_SWIFT["language"]["desc_customfieldgroups"] , 2);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderCustomFieldGroupForm(INSERT);

	$template->assign("backurl", "index.php?_m=core&_a=managecfgroups");
	$interface->adminFooter();	


/**
* ###############################################
* EDIT CUSTOM FIELD GROUP
* ###############################################
*/
} else if ($eventaction == "editcfgroup") {
	// First fetch all the group details
	$_customfieldgroup = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."customfieldgroups` WHERE `customfieldgroupid` = '". intval($_REQUEST["customfieldgroupid"]) ."';");
	if (empty($_customfieldgroup["customfieldgroupid"]))
	{
		trigger_error($_SWIFT["language"]["invalidcfgroup"], E_USER_ERROR);
	}
//Mahesh Slaria: Staff & user ticket creation
	if ($_customfieldgroup["grouptype"] == CUSTOMFIELD_USERTICKET || $_customfieldgroup["grouptype"] == CUSTOMFIELD_STAFFTICKET || $_customfieldgroup["grouptype"] == CUSTOMFIELD_STAFFUSERTICKET)
	{
		// Load the links
		$_customfieldgroup["departmentidlist"] = array();
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfielddeplinks` WHERE `customfieldgroupid` = '". intval($_customfieldgroup["customfieldgroupid"]) ."';");
		while ($dbCore->nextRecord())
		{
			$_customfieldgroup["departmentidlist"][] = $dbCore->Record["departmentid"];
		}
	}

	if ($_POST["step"] == "1")
	{
		if (trim($_POST["title"]) == "" || trim($_POST["displayorder"]) == "" || trim($_POST["grouptype"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);

			updateCustomFieldGroup($_customfieldgroup["customfieldgroupid"], $_POST["title"], $_POST["grouptype"], $_POST["displayorder"], $_POST["departmentid"]);

			printRedirect(sprintf($_SWIFT["language"]["cfgroupupdateconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=core&_a=managecfgroups&updatecfgroup=".urlencode($_POST["title"]));
			exit;
		}
	}

	$_POST = array_merge($_POST, $_customfieldgroup);

	$interface->adminHeader($_SWIFT["language"]["customfields"]." > ".$_SWIFT["language"]["editgroup"], 1);

	$interface->adminNavBar($_SWIFT["language"]["editgroup"], $_SWIFT["language"]["desc_customfieldgroups"] , 2);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderCustomFieldGroupForm(EDIT);

	$template->assign("backurl", "index.php?_m=core&_a=managecfgroups");
	$interface->adminFooter();	




/**
* ###############################################
* MANAGE CUSTOM FIELDS
* ###############################################
*/
} else if ($eventaction == "managecfields") {
	if ($_GET["do"] == "delete" && $_GET["customfieldid"] != "")
	{
		$infomessage = $_SWIFT["language"]["cfdelconfirm"];
		deleteCustomFields(array($_GET["customfieldid"]));
	}

	if (trim($_REQUEST["insertcfield"]) != "")
	{
		$infomessage = sprintf($_SWIFT["language"]["cfieldinsertconfirm"], htmlspecialchars($_GET["insertcfield"]));
	} else if (trim($_REQUEST["updatecfield"]) != "") {
		$infomessage = sprintf($_SWIFT["language"]["cfieldupdateconfirm"], htmlspecialchars($_GET["updatecfield"]));
	}

	$options["recordsperpage"] = "10";
	$options["sortby"] = "customfields.displayorder";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteCustomFields";

	$options["idname"] = "customfieldid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["fieldtitle"];
	$options["advancedsearch"][0]["query"] = 'SELECT *, customfields.title AS fieldtitle, customfields.displayorder AS fielddisplayorder, customfieldgroups.title AS grouptitle FROM `'. TABLE_PREFIX .'customfields` AS customfields LEFT JOIN `'. TABLE_PREFIX .'customfieldgroups` AS customfieldgroups ON (customfields.customfieldgroupid = customfieldgroups.customfieldgroupid) WHERE customfields.title LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["advancedsearch"][1]["title"] = $_SWIFT["language"]["grouptitle"];
	$options["advancedsearch"][1]["query"] = 'SELECT *, customfields.title AS fieldtitle, customfields.displayorder AS fielddisplayorder, customfieldgroups.title AS grouptitle FROM `'. TABLE_PREFIX .'customfields` AS customfields LEFT JOIN `'. TABLE_PREFIX .'customfieldgroups` AS customfieldgroups ON (customfields.customfieldgroupid = customfieldgroups.customfieldgroupid) WHERE customfieldgroups.title LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_customFields";

	$fields[0]["name"] = "customfields.title";
	$fields[0]["title"] = $_SWIFT["language"]["fieldtitle"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "customfieldgroups.title";
	$fields[1]["title"] = $_SWIFT["language"]["grouptitle"];
	$fields[1]["width"] = "180";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "customfields.fieldtype";
	$fields[2]["title"] = $_SWIFT["language"]["fieldtype"];
	$fields[2]["width"] = "150";
	$fields[2]["align"] = "center";

	$fields[3]["name"] = "customfields.displayorder";
	$fields[3]["title"] = $_SWIFT["language"]["fielddisplayorder"];
	$fields[3]["width"] = "120";
	$fields[3]["align"] = "center";

	$fields[4]["type"] = "custom";
	$fields[4]["name"] = "options";
	$fields[4]["title"] = $_SWIFT["language"]["options"];
	$fields[4]["width"] = "160";
	$fields[4]["align"] = "center";

	$grid = new Grid();

	$interface->adminHeader($_SWIFT["language"]["customfields"]." > ".$_SWIFT["language"]["managefields"], 1);

	$interface->adminNavBar($_SWIFT["language"]["managefields"], $_SWIFT["language"]["desc_customfields"] , 2);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	$grid->start("customfields", $_SWIFT["language"]["fieldlist"], 'SELECT *, customfields.title AS fieldtitle, customfields.displayorder AS fielddisplayorder, customfieldgroups.title AS grouptitle FROM `'. TABLE_PREFIX .'customfields` AS customfields LEFT JOIN `'. TABLE_PREFIX .'customfieldgroups` AS customfieldgroups ON (customfields.customfieldgroupid = customfieldgroups.customfieldgroupid) $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'customfields`;', 'SELECT *, customfields.title AS fieldtitle, customfields.displayorder AS fielddisplayorder, customfieldgroups.title AS grouptitle FROM `'. TABLE_PREFIX .'customfields` AS customfields LEFT JOIN `'. TABLE_PREFIX .'customfieldgroups` AS customfieldgroups ON (customfields.customfieldgroupid = customfieldgroups.customfieldgroupid) WHERE customfields.title LIKE \'%$_searchstr%\' $_sortjoin;', $fields, $options);
	
	$grid->display("customfields");
	$interface->adminFooter();




/**
* ###############################################
* INSERT NEW CUSTOM FIELD
* ###############################################
*/
} else if ($eventaction == "insertcfield") {
	if ($_POST["step"] == "2")
	{
		if (empty($_POST["title"]) || empty($_POST["fieldname"]))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
			$_POST["step"] = 1;
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);	

			$customfieldid = insertCustomField($_POST["customfieldgroupid"], $_POST["fieldtype"], $_POST["title"], $_POST["fieldname"], $_POST["defaultvalue"], $_POST["displayorder"], $_POST["isrequired"], $_POST["usereditable"], $_POST["staffeditable"], $_POST["regexpvalidate"], $_POST["fieldlist"], $_POST["selectedfield"], $_POST["description"]);

			printRedirect(sprintf($_SWIFT["language"]["cfieldinsertconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=core&_a=managecfields&insertcfield=".urlencode($_POST["title"]));
			exit;
		}
	}
	
	if ($_POST["step"] == "1") {
		if (empty($_POST["customfieldgroupid"]))
		{
			unset($_POST["step"]);
		} else {
			$interface->adminHeader($_SWIFT["language"]["customfields"]." > ".$_SWIFT["language"]["insertfield"], 1);

			$interface->adminNavBar($_SWIFT["language"]["insertfieldstep2"], $_SWIFT["language"]["desc_customfields"] , 2);
			
			printInfoBox($infomessage);
			printErrorBox($errormessage);

			printFormStart();
			printMainTableHeader($_SWIFT["language"]["fielddetails"]);

			printTextRow("title", $_SWIFT["language"]["fieldtitle"], $_SWIFT["language"]["desc_fieldtitle"], "text", $_POST["title"]);
			if ($_POST["fieldtype"] == FIELD_CUSTOM)
			{
				// Ask for field name
				printTextRow("fieldname", $_SWIFT["language"]["fieldname"], $_SWIFT["language"]["desc_fieldname"], "text", $_POST["fieldname"]);
			} else {
				addHiddenField("fieldname", substr(buildHash(), 1, 10));
			}

			if ($_POST["fieldtype"] == FIELD_TEXT || $_POST["fieldtype"] == FIELD_PASSWORD)
			{
				printTextRow("defaultvalue", $_SWIFT["language"]["defaultvalue"], $_SWIFT["language"]["desc_defaultvalue"], "text", $_POST["defaultvalue"]);			
			} else if ($_POST["fieldtype"] == FIELD_TEXTAREA) {
				printTextareaRow("defaultvalue", $_SWIFT["language"]["defaultvalue"], $_SWIFT["language"]["desc_defaultvalue"], $_POST["defaultvalue"]);				
			}			
			//----------Description----->
			printTextRow("description", $_SWIFT["language"]["description"], $_SWIFT["language"]["desc_description"], "text", $_POST["description"]);
			//-------------------------->
			// Get the last display order
			$_disporder = $dbCore->queryFetch("SELECT `displayorder` FROM `". TABLE_PREFIX ."customfields` ORDER BY `displayorder` DESC LIMIT 1;");
			if (empty($_disporder["displayorder"]))
			{
				$_POST["displayorder"] = 1;
			} else {
				$_POST["displayorder"] = $_disporder["displayorder"]+1;
			}
			printNumberRow("displayorder", $_SWIFT["language"]["fielddisplayorder"], $_SWIFT["language"]["desc_fielddisplayorder"], $_POST["displayorder"]);

			printYesNoRow("isrequired", $_SWIFT["language"]["isrequired"], $_SWIFT["language"]["desc_isrequired"], iif(empty($_POST["isrequired"]), false, $_POST["isrequired"]));

			if (trim($_POST["usereditable"]) == "")
			{
				$usereditable = true;
			} else {
				$usereditable = $_POST["usereditable"];
			}
			if (trim($_POST["staffeditable"]) == "")
			{
				$staffeditable = true;
			} else {
				$staffeditable = $_POST["staffeditable"];
			}

			printYesNoRow("usereditable", $_SWIFT["language"]["usereditable"], $_SWIFT["language"]["desc_usereditable"], $usereditable);
			printYesNoRow("staffeditable", $_SWIFT["language"]["staffeditable"], $_SWIFT["language"]["desc_staffeditable"], $staffeditable);
			
			printTextRow("regexpvalidate", $_SWIFT["language"]["regexpvalidate"], $_SWIFT["language"]["desc_regexpvalidate"], "text", $_POST["regexpvalidate"]);

			if ($_POST["fieldtype"] != FIELD_TEXT && $_POST["fieldtype"] != FIELD_PASSWORD && $_POST["fieldtype"] != FIELD_TEXTAREA && $_POST["fieldtype"] != FIELD_CUSTOM)
			{
				// Field options
				printDescRow($_SWIFT["language"]["fieldoptions"]);

				$fieldcount = 8;
				$fieldvalue = '<table width="100%"  border="0" cellspacing="0" cellpadding="2">
					  <tr>
						<td><span class="tabletitle">'. $_SWIFT["language"]["optionvalues"] .'</span> </td>
						<td width="250" align="center"><span class="tabletitle">'. $_SWIFT["language"]["optiondisplayorder"] .'</span> </td>
						<td width="250" align="center"><span class="tabletitle">'. $_SWIFT["language"]["optionisselected"] .'</span> </td>
					  </tr>';


				for ($ii=0; $ii<$fieldcount; $ii++)
				{
					if ($_POST["fieldtype"] == FIELD_CHECKBOX || $_POST["fieldtype"] == FIELD_SELECTMULTIPLE)
					{
						$selecteddata = '<td align="center"><input name="fieldlist['. $ii .'][2]" type="checkbox" value="1"'. iif($ii==0, " checked") .'></td>';
					} else {
						$selecteddata = '<td align="center"><input name="selectedfield" type="radio" value="'. $ii .'"'. iif($ii==0, " checked") .'></td>';
					}
					$fieldvalue .= '
					  <tr>
						<td><input type="text" name="fieldlist['.$ii.'][0]" class="swifttext" size="30"></td>
						<td align="center"><input name="fieldlist['.$ii.'][1]" type="text" size="5" class="swifttext" value="'. ($ii+1) .'"></td>'. $selecteddata .'</tr>';
				}
				$fieldvalue .= '</table>';

				$rowlist[0]["align"] = "left";
				$rowlist[0]["nowrap"] = true;
				$rowlist[0]["colspan"] = "2";
				$rowlist[0]["value"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td width="100%">'. $fieldvalue .'</td>
				  </tr>
				</table>';

				printDataRow($rowlist, getRowBG());
			}

			printSubmitRow($_SWIFT["language"]["insertfield"]);

			printMainTableFooter();

			addHiddenField("_m", "core");
			addHiddenField("_a", "insertcfield");
			addHiddenField("step", "2");
			addHiddenField("customfieldgroupid", $_POST["customfieldgroupid"]);
			addHiddenField("fieldtype", $_POST["fieldtype"]);
			printFormEnd();

			$template->assign("backurl", "index.php?_m=core&_a=insertcfield");
			$interface->adminFooter();			
		}
	}

	if (empty($_POST["step"]))
	{
		$interface->adminHeader($_SWIFT["language"]["customfields"]." > ".$_SWIFT["language"]["insertfield"], 1);

		$interface->adminNavBar($_SWIFT["language"]["insertfieldstep1"], $_SWIFT["language"]["desc_customfields"] , 2);

		// ======= GROUP ARRAY LOADING =======
		$groupindex = 0;
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfieldgroups` ORDER BY `displayorder` ASC;");
		while ($dbCore->nextRecord())
		{
			$options[$groupindex]["title"] = $dbCore->Record["title"];
			$options[$groupindex]["value"] = $dbCore->Record["customfieldgroupid"];
			if ($dbCore->Record["customfieldgroupid"] == $_GET["customfieldgroupid"])
			{
				$options[$groupindex]["selected"] = true;
			}
			$groupindex++;
		}

		if (!$groupindex)
		{
			// No groups added
			$options[0]["title"] = $_SWIFT["language"]["nogroupadded"];
			$options[0]["value"] = "";
			$errormessage = $_SWIFT["language"]["erroraddcfgroup"];
		}

		printInfoBox($infomessage);
		printErrorBox($errormessage);

		printFormStart();
		printMainTableHeader($_SWIFT["language"]["fielddetails"]);

		// ======= CUSTOM FIELD GROUPS =======
		printSelectRow("customfieldgroupid", $_SWIFT["language"]["customfieldgroup"], $_SWIFT["language"]["desc_customfieldgroup"], $options);

		// ======= BUILD THE FIELD LIST =======
		$fields[] = array(FIELD_TEXT, $_SWIFT["language"]["field_text"], $_SWIFT["language"]["desc_field_text"], "icon_cfeditbox.gif");
		$fields[] = array(FIELD_TEXTAREA, $_SWIFT["language"]["field_textarea"], $_SWIFT["language"]["desc_field_textarea"], "icon_cfeditbox.gif");
		$fields[] = array(FIELD_PASSWORD, $_SWIFT["language"]["field_password"], $_SWIFT["language"]["desc_field_password"], "icon_cfpassword.gif");
		$fields[] = array(FIELD_CHECKBOX, $_SWIFT["language"]["field_checkbox"], $_SWIFT["language"]["desc_field_checkbox"], "icon_cfcheckbox.gif");
		$fields[] = array(FIELD_RADIO, $_SWIFT["language"]["field_radio"], $_SWIFT["language"]["desc_field_radio"], "icon_cfradio.gif");
		$fields[] = array(FIELD_SELECT, $_SWIFT["language"]["field_select"], $_SWIFT["language"]["desc_field_select"], "icon_cfselect.gif");
		$fields[] = array(FIELD_SELECTMULTIPLE, $_SWIFT["language"]["field_selectmultiple"], $_SWIFT["language"]["desc_field_selectmultiple"], "icon_cfselectmultiple.gif");
		$fields[] = array(FIELD_CUSTOM, $_SWIFT["language"]["field_custom"], $_SWIFT["language"]["desc_field_custom"], "icon_cfcustom.gif");
		
		printDescRow($_SWIFT["language"]["fieldtype"]);
		$rowindex = 0;
		foreach ($fields as $key=>$val)
		{
			$rowlist = array();

			$rowlist[0]["align"] = "left";
			$rowlist[0]["nowrap"] = true;
			$rowlist[0]["colspan"] = "2";
			$rowlist[0]["value"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="2">
  <tr>
    <td width="1%"><input name="fieldtype" type="radio" value="'. $val[0] .'"'. iif($rowindex==0, ' checked') .'></td>
    <td width="99%"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td width="1"><img src="'. $_SWIFT["themepath"]. $val[3] .'" border="0" /></td>
        <td><span class="tabletitle">&nbsp;'. $val[1] .'</span></td>
      </tr>
    </table></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><span class="tabledescription">'. $val[2] .'</span></td>
  </tr>
</table>';

			printDataRow($rowlist, getRowBG());
			
			$rowindex++;
		}

		printSubmitRow($_SWIFT["language"]["next"]);

		printMainTableFooter();

		addHiddenField("_m", "core");
		addHiddenField("_a", "insertcfield");
		addHiddenField("step", "1");
		printFormEnd();

		$template->assign("backurl", "index.php?_m=core&_a=managecfields");
		$interface->adminFooter();
	}	






/**
* ###############################################
* EDIT CUSTOM FIELD
* ###############################################
*/
} else if ($eventaction == "editcfield") {
	// First fetch all the data for this field
	$_customfield = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."customfields` WHERE `customfieldid` = '". intval($_REQUEST["customfieldid"]) ."';");
	if (empty($_customfield["customfieldid"]))
	{
		trigger_error($_SWIFT["language"]["invalidcustomfield"], E_USER_ERROR);
	}

	// Now fetch all the field options
	$_fieldoptions = array();
	if ($_POST["fieldtype"] != FIELD_TEXT && $_POST["fieldtype"] != FIELD_PASSWORD && $_POST["fieldtype"] != FIELD_TEXTAREA && $_POST["fieldtype"] != FIELD_CUSTOM)
	{
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfieldoptions` WHERE `customfieldid` = '". intval($_customfield["customfieldid"]) ."' ORDER BY `displayorder` ASC;");
		while ($dbCore->nextRecord())
		{
			$_fieldoptions[] = $dbCore->Record;
		}
	}

	if ($_POST["step"] == "1")
	{
		if (empty($_POST["title"]) || empty($_POST["fieldname"]))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
			$_POST["step"] = 1;
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);	

			updateCustomField($_customfield["customfieldid"], $_POST["customfieldgroupid"], $_POST["title"], $_POST["fieldname"], $_POST["defaultvalue"], $_POST["displayorder"], $_POST["isrequired"], $_POST["usereditable"], $_POST["staffeditable"], $_POST["regexpvalidate"], $_POST["fieldlist"], $_POST["selectedfield"], $_POST["description"]);

			printRedirect(sprintf($_SWIFT["language"]["cfieldupdateconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=core&_a=managecfields&updatecfield=".urlencode($_POST["title"]));
			exit;
		}
	}
	
	$interface->adminHeader($_SWIFT["language"]["customfields"]." > ".$_SWIFT["language"]["editcfield"], 1);

	$interface->adminNavBar($_SWIFT["language"]["editcfield"], $_SWIFT["language"]["desc_customfields"] , 2);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["fielddetails"]);

	$options = array();
	$index = 0;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."customfieldgroups` ORDER BY `title` ASC;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["customfieldgroupid"];
		if ($_customfield["customfieldgroupid"] == $dbCore->Record["customfieldgroupid"])
		{
			$options[$index]["selected"] = true;
		}
		$index++;
	}

	printSelectRow("customfieldgroupid", $_SWIFT["language"]["cfgroupd"], $_SWIFT["language"]["desc_cfgroupd"], $options);
	unset($options);

	printTextRow("title", $_SWIFT["language"]["fieldtitle"], $_SWIFT["language"]["desc_fieldtitle"], "text", $_customfield["title"]);

	if ($_customfield["fieldtype"] == FIELD_CUSTOM)
	{
		// Ask for field name
		printTextRow("fieldname", $_SWIFT["language"]["fieldname"], $_SWIFT["language"]["desc_fieldname"], "text", $_customfield["fieldname"]);
	} else {
		addHiddenField("fieldname", $_customfield["fieldname"]);
	}

	if ($_customfield["fieldtype"] == FIELD_TEXT || $_customfield["fieldtype"] == FIELD_PASSWORD)
	{
		printTextRow("defaultvalue", $_SWIFT["language"]["defaultvalue"], $_SWIFT["language"]["desc_defaultvalue"], "text", $_customfield["defaultvalue"]);
	} else if ($_customfield["fieldtype"] == FIELD_TEXTAREA) {
		printTextareaRow("defaultvalue", $_SWIFT["language"]["defaultvalue"], $_SWIFT["language"]["desc_defaultvalue"], $_customfield["defaultvalue"]);
	}
	//----------Description----->
	printTextRow("description", $_SWIFT["language"]["description"], $_SWIFT["language"]["desc_description"], "text", $_customfield["description"]);
	//-------------------------->
	
	printNumberRow("displayorder", $_SWIFT["language"]["fielddisplayorder"], $_SWIFT["language"]["desc_fielddisplayorder"], $_customfield["displayorder"]);

	printYesNoRow("isrequired", $_SWIFT["language"]["isrequired"], $_SWIFT["language"]["desc_isrequired"], iif($_customfield["isrequired"]==1, true, false));

	printYesNoRow("usereditable", $_SWIFT["language"]["usereditable"], $_SWIFT["language"]["desc_usereditable"], iif($_customfield["usereditable"]==1, true, false));
	printYesNoRow("staffeditable", $_SWIFT["language"]["staffeditable"], $_SWIFT["language"]["desc_staffeditable"], iif($_customfield["staffeditable"]==1, true, false));
		
	printTextRow("regexpvalidate", $_SWIFT["language"]["regexpvalidate"], $_SWIFT["language"]["desc_regexpvalidate"], "text", $_customfield["regexpvalidate"]);

	if ($_customfield["fieldtype"] != FIELD_TEXT && $_customfield["fieldtype"] != FIELD_PASSWORD && $_customfield["fieldtype"] != FIELD_TEXTAREA && $_customfield["fieldtype"] != FIELD_CUSTOM)
	{
		// Field options
		printDescRow($_SWIFT["language"]["fieldoptions"]);

		$fieldcount = count($_fieldoptions)+5;
		$fieldvalue = '<table width="100%"  border="0" cellspacing="0" cellpadding="2">
			  <tr>
				<td><span class="tabletitle">'. $_SWIFT["language"]["optionvalues"] .'</span> </td>
				<td width="250" align="center"><span class="tabletitle">'. $_SWIFT["language"]["optiondisplayorder"] .'</span> </td>
				<td width="250" align="center"><span class="tabletitle">'. $_SWIFT["language"]["optionisselected"] .'</span> </td>
			  </tr>';


		for ($ii=0; $ii<$fieldcount; $ii++)
		{
			$_fieldopt = $_fieldoptions[$ii];

			if ($_customfield["fieldtype"] == FIELD_CHECKBOX || $_customfield["fieldtype"] == FIELD_SELECTMULTIPLE)
			{
				$selecteddata = '<td align="center"><input name="fieldlist['. $ii .'][2]" type="checkbox" value="1"'. iif($_fieldopt["isselected"]==1, " checked") .'></td>';
			} else {
				$selecteddata = '<td align="center"><input name="selectedfield" type="radio" value="'. $ii .'"'. iif($_fieldopt["isselected"]==1, " checked") .'></td>';
			}

			if (isset($_fieldopt["displayorder"]))
			{
				$_disporder = $_fieldopt["displayorder"];
			} else {
				$_disporder = $ii+1;
			}

			$fieldvalue .= '
			  <tr>
				<td><input type="text" name="fieldlist['.$ii.'][0]" class="swifttext" size="30" value="'. $_fieldopt["optionvalue"] .'"></td>
				<td align="center"><input name="fieldlist['.$ii.'][1]" type="text" size="5" class="swifttext" value="'. $_disporder .'"></td>'. $selecteddata .'</tr>';
		}
		$fieldvalue .= '</table>';

		$rowlist[0]["align"] = "left";
		$rowlist[0]["nowrap"] = true;
		$rowlist[0]["colspan"] = "2";
		$rowlist[0]["value"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="0">
		  <tr>
			<td width="100%">'. $fieldvalue .'</td>
		  </tr>
		</table>';

		printDataRow($rowlist, getRowBG());
	}

	printSubmitRow($_SWIFT["language"]["updatefield"]);

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", "editcfield");
	addHiddenField("step", "1");
	addHiddenField("customfieldid", $_customfield["customfieldid"]);
	printFormEnd();

	$template->assign("backurl", "index.php?_m=core&_a=managecfields");
	$interface->adminFooter();
}
?>